package kos.robert.screens;

import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

import kos.robert.loader.Debug;

public class ScreenManager {
	private GraphicsDevice vc;

	// give vc access to monitor screen
	public ScreenManager() {
		GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
		vc = env.getDefaultScreenDevice();
	}

	// get all compatible DM
	public DisplayMode[] getCompatibleDisplayModes() {
		return vc.getDisplayModes();
	}

	public DisplayMode findFirsCompatibleDisplaymode(DisplayMode modes[]) {
		DisplayMode[] supportedModes = vc.getDisplayModes();
		for (int x = 0; x < modes.length; x++) {
			for (int y = 0; y < supportedModes.length; y++) {
				if (supportedModes[y].equals(modes[x])) {
					return supportedModes[y];
				}
			}
		}
		return null;
	}

	public DisplayMode getCurrentDisplayMode() {
		return vc.getDisplayMode();
	}

	// make frame full screen
	public void setFullScreen(DisplayMode dm) {
		JFrame f = new JFrame();
		f.setUndecorated(true);
		f.setIgnoreRepaint(true);
		f.setResizable(false);
		vc.setFullScreenWindow(f);

		if (dm != null && vc.isDisplayChangeSupported()) {
			try {
				vc.setDisplayMode(dm);
			} catch (Exception e) {
			}
		}
		f.createBufferStrategy(2);
	}
	
	public void setDisplayMode(DisplayMode dm){
		if (dm != null && vc.isDisplayChangeSupported()) {
			try {
				vc.setDisplayMode(dm);
			} catch (Exception e) {
			}
		}
	}

	// set Graphics object = to this
	public Graphics2D getGraphics() {
		Window w = vc.getFullScreenWindow();
		
		if (w != null) {
			BufferStrategy bs = w.getBufferStrategy();
			return (Graphics2D) bs.getDrawGraphics();
		} else {
			return null;
		}
	}

	// updates screen
	public void update() {
		Window w = vc.getFullScreenWindow();
		if (w != null) {
			BufferStrategy bs = w.getBufferStrategy();
			if (!bs.contentsLost()) {
				bs.show();
			}
		}
	}

	// returns full screen window
	public Window getFullScreenWindow() {
		return vc.getFullScreenWindow();
	}

	public int getWidth() {
		Window w = vc.getFullScreenWindow();
		if (w != null) {
			return w.getWidth();
		} else {
			return 0;
		}
	}

	public int getHeight() {
		Window w = vc.getFullScreenWindow();
		if (w != null) {
			return w.getHeight();
		} else {
			return 0;
		}
	}

	// get out of fullscreen
	public void restoreScreen() {
		Window w = vc.getFullScreenWindow();
		if (w != null) {
			w.dispose();
		}
		vc.setFullScreenWindow(null);
	}

	// create image compatible with monitor
	public BufferedImage createCompatibleImage(int w, int h, int t) {
		Window window = vc.getFullScreenWindow();
		if (window != null) {
			GraphicsConfiguration gc = window.getGraphicsConfiguration();
			return gc.createCompatibleImage(w, h, t);
		} else {
			return null;
		}
	}
}
